// pages/search/search.js
import {
  KeywordModel
} from '../../models/keyword.js';

import {
  ContentModel
} from '../../models/content.js';

import {
  Lock
} from '../../models/lock.js';

import {
  UserModel
} from '../../models/user.js';

import {
  enums
} from '../../utils/enums.js';

const util = require('../../utils/util.js');

const content = new ContentModel();

const user = new UserModel();

const keyword = new KeywordModel();

const lock = new Lock();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
      "tabName": "内容",
      "key": "1"
    }, {
      "tabName": "用户",
      "key": "2"
    }],
    historyWords: [],
    q: '',
    activeKey: "1",
    searching: false,
    contentPageIndex: 1,
    contentTotal: 0,
    countContents: [],
    contents: [],
    userPageIndex: 1,
    userTotal: 0,
    users: [],
    placeholder: "输入关键字搜索",
    contentLoading: {
      "show": false,
      "type": "loading"
    },
    usersLoading: {
      "show": false,
      "type": "loading"
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let hotWords = wx.getStorageSync(enums.hot);

    if (options.hasOwnProperty("q")) {
      this.setData({
        q: options.q
      });

      this._init();
      this._loadContentInfo();
      this._loadUserInfo();

      keyword.addToHistory(options.q);
    } else {
      this.setData({
        historyWords: keyword.getHistory(),
        hotWords: hotWords
      });
    }

    if (hotWords.length > 0) {
      let keyword = util.searchPlaceholder(hotWords);
      this.setData({
        placeholder: `大家都在搜"${keyword}"`
      })
    }
  },

  _loadContentInfo() {

    let that = this;

    content.search(that.data.q, that.data.contentPageIndex).then(res => {
      that._showResult();

      that._closeContentLoadMoreTip();

      that.setData({
        contentTotal: res.data.totalElements,
      })

      if (res.data.content.length > 0) {
        // 数组合并,用于计算是否全部加载数据
        that.data.countContents.push.apply(that.data.countContents, res.data.content);
        that.setData({
          // 用于页面展示
          contents: res.data.content,
          // 用于计算是否全部加在
          countContents: that.data.countContents
        });
      }
    });
  },

  _loadUserInfo() {

    let that = this;

    user.search(that.data.q, that.data.userPageIndex).then(res => {

      that._showResult();

      that._closeUsersLoadMoreTip();

      that.setData({
        userTotal: res.data.total,
      })

      if (res.data.content.length > 0) {
        //数组合并
        that.data.users.push.apply(that.data.users, res.data.content);
        that.setData({
          users: that.data.users
        });
      }

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.activeKey === '1') {
      if (this.data.contentTotal == this.data.countContents.length) {
        // 加载全部
        this._showContentLoadedAllTip();
      } else {
        this.data.contentPageIndex++;
        this._showContentLoadMoreTip();
        this._loadContentInfo();
      }
    } else {
      if (this.data.userTotal == this.data.users.length) {
        // 加载全部
        this._showUsersLoadedAllTip();
      } else {
        this.data.userPageIndex++;
        this._showUsersLoadMoreTip();
        this._loadUserInfo();
      }
    }
  },

  /**
   * 点击查询
   * @param {Object} e 
   */
  onConfirm(e) {

    const q = e.detail.value || e.currentTarget.dataset.text;

    if (!q) {
      return;
    }

    this.setData({
      q: q
    });

    this._init();
    this._loadContentInfo();
    this._loadUserInfo();

    keyword.addToHistory(q);
  },

  /**
   * 初始化
   */
  _init() {
    this.setData({
      contents: [],
      users: [],
      countContents: [],
      contentPageIndex: 1,
      userPageIndex: 1
    })
  },

  _showResult: function () {
    this.setData({
      searching: true
    });
  },

  _closeResult: function () {
    this.setData({
      searching: false,
      q: ''
    });
  },
  changeTabs(e) {
    let activeKey = e.detail.activeKey;
    this.setData({
      activeKey: activeKey
    })
  },
  _showContentLoadedAllTip() {
    this.setData({
      contentLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeContentLoadedAllTip() {
    this.setData({
      contentLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showContentLoadMoreTip() {
    this.setData({
      contentLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeContentLoadMoreTip() {
    this.setData({
      contentLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },
  _showUsersLoadedAllTip() {
    this.setData({
      usersLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeUsersLoadedAllTip() {
    this.setData({
      usersLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showUsersLoadMoreTip() {
    this.setData({
      usersLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeUsersLoadMoreTip() {
    this.setData({
      usersLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },

  toDetail(e) {
    let params = e.detail;
    // 跳转到详情页
    wx.navigateTo({
      url: `../detail/detail?id=${params.id}`,
    });
  },
  onProfile(e) {
    let userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `../profile/profile?userId=${userId}`,
    })
  },
  onFollow(e) {

    let that = this;

    wx.showLoading({
      title: '加载中...',
    })

    let userId = e.currentTarget.dataset.userId;
    let follow = e.currentTarget.dataset.follow;
    let index = e.currentTarget.dataset.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    user.self(userId).then(res => {

      wx.hideLoading();

      if (res.data) {
        wx.showToast({
          title: '不能关注自己',
          icon: 'none',
          duration: 2000
        });
      } else {
        user.follow(userId, follow).then(followInfo => {

          setTimeout(() => {
            that.data.users[index].follow = follow ? !followInfo.data : followInfo.data;
            that.setData({
              users: that.data.users
            })

          }, 600);

          lock.unlock();
        }).catch(err => {
          console.log(err);
          lock.unlock();
        });
      }
      lock.unlock();
    }).catch(err => {
      lock.unlock();
    });
  },
  onCancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  onClear() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除历史搜索吗？',
      success: function (sm) {
        if (sm.confirm) {
          keyword.clearHistory();
          that.setData({
            historyWords: []
          })
        }
      }
    })
  }
})